package br.unisul.com.daos;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import br.unisul.com.bean.ClienteBean;
import br.unisul.com.bean.PersistenceManager;

public class ClienteDAO {
	EntityManagerFactory emf;

	public ClienteDAO() {
		emf = PersistenceManager.getInstance().getEntityManagerFactory();
	}
	
	public List<ClienteBean> listAll(){
		EntityManager em = emf.createEntityManager();
		try{
			return em.createQuery("from ClienteBean", ClienteBean.class).getResultList();
		}finally{
			em.close();
		}
	}
	
	public void salvar(ClienteBean cliente){
		EntityManager em = emf.createEntityManager();
		try{
			EntityTransaction et = em.getTransaction();
			try{
				et.begin();
				em.persist(cliente);
				et.commit();
			}finally{
				if(et.isActive())
					et.rollback();
			}
		}finally{
			em.close();
		}		
	}
	
	public void excluir(Long id){
		EntityManager em = emf.createEntityManager();
		try{
			EntityTransaction et = em.getTransaction();
			try{
				ClienteBean cliente = em.find(ClienteBean.class, id);
				if(cliente != null){
					et.begin();
					em.remove(cliente);
					et.commit();
				}
			}finally{
				if(et.isActive())
					et.rollback();
			}
		}finally{
			em.close();
		}
	}
	
	public void editar(ClienteBean cliente){
		EntityManager em = emf.createEntityManager();
		try{
			EntityTransaction et = em.getTransaction();
			try{
				ClienteBean clienteBusca = buscarClientePeloCPF(cliente.getCpf());
				cliente.setId(clienteBusca.getId());
				
				ClienteBean clienteEncontrado = em.find(ClienteBean.class, cliente.getId());
				
				if(clienteEncontrado != null){
					et.begin();
					clienteEncontrado.setNome(cliente.getNome());
					clienteEncontrado.setEndereco(cliente.getEndereco());
					clienteEncontrado.setCpf(cliente.getCpf());
					et.commit();
				}
			}finally{
				if(et.isActive())
					et.rollback();
			}
		}finally{
			em.close();
		}
	}
	
	public ClienteBean buscarClientePeloCPF(String cpf){
		EntityManager em = emf.createEntityManager();
		ClienteBean cliente = null;
		try{
			Query query = em.createQuery("select c from ClienteBean c where c.cpf = :cpf");
			query.setParameter("cpf", cpf);
			cliente = (ClienteBean) query.getSingleResult();
		}catch(Exception e){
			return cliente;
		}finally{
			em.close();
		}
		
		return cliente;
	}
}
